package com.xiaomengkuan.user.controller;

import com.xiaomengkuan.user.entity.pojo.VerifyCode;
import com.xiaomengkuan.common.util.R;
import com.xiaomengkuan.user.util.VerifyCodeGenerate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.codec.binary.Base64;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author Faraj Mujey
 * -- Creation Time: 2021-01-16 1:10 下午, File Encoding: utf8 --
 */
@RestController
@RequestMapping("user")
@Api(tags = "图片验证码")
@Log4j2
public class CaptchaController {
    @Resource
    VerifyCodeGenerate verifyCodeGenerate;

    /**
     * 获取图片验证码
     * @return R
     */
    @ApiOperation("获取图片验证码")
    @GetMapping("captcha")
    public R verifyCode() {
        try {
            Map<String, Object> map = new HashMap<>();
            //设置长宽
            VerifyCode verifyCode = verifyCodeGenerate.generate(80, 28);
            String code = verifyCode.getCode();
            map.put("code",code);
            map.put("bytes", Base64.encodeBase64String(verifyCode.getImgBytes()));
            return R.ok().detail("成功生成验证码图片").put(map);
        } catch (IOException e) {
            log.error("admin/user/verifyCode error {}" ,  e.getMessage());
            return R.err().detail(e.getMessage());
        }
    }
}
